package com.hibernate.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imprenta.model.PedidoBase;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;

public class ReportServlet extends HttpServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("deprecation")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		 ArrayList<PedidoBase> lstPedido = new ArrayList<PedidoBase>();
		 PedidoBase p = new PedidoBase();p.setPedidoId("1");p.setNombreCompleto("javier");p.setNombreProducto("flyers");p.setFecha("2012");
		 p.setCantidad(10);p.setTotal(10);lstPedido.add(p);
		 
		ServletOutputStream outputStream = resp.getOutputStream();
		File reportFile = new File(getServletConfig().getServletContext().getRealPath("/com/test/report/report-pedido.jasper"));
		@SuppressWarnings("unused")
		JasperReport reporte;
		byte[] fichero = null;
		
		try {
			reporte = (JasperReport) JRLoader.loadObject(getClass().getResource("/com/test/report/report-pedido.jasper").getPath());
			fichero = JasperRunManager.runReportToPdf(reportFile.getPath(), null, new JRBeanCollectionDataSource(lstPedido));
			resp.setContentType("application/pdf");
			resp.setContentLength(fichero.length);
			resp.setHeader("Content-disposition", "atachment;filename=\"reporte.pdf\";");
			
			outputStream.write(fichero, 0, fichero.length);
			outputStream.flush();
			outputStream.close();
			
		} catch (JRException e) {
			// TODO Auto-generated catch block
		    StringWriter stringWriter = new StringWriter();
		      PrintWriter printWriter = new PrintWriter(stringWriter);
		      e.printStackTrace(printWriter);
		      resp.setContentType("text/plain");
		      resp.getOutputStream().print(stringWriter.toString());
		}
		
	}
}
